package com.weike.gatewei.filter;


import cn.hutool.json.JSONObject;
import com.weike.yuanding.core.domain.R;
import com.weike.yuanding.utils.JwtHelper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: UserIdForwardingFilter
 * @Author: YuanDing
 * @Date: 2025/4/2 22:08
 * @Description:
 */

@Order(1)
@Component
@Data
@ConfigurationProperties(prefix = "jwt.token") //批量从application.yaml中加载值到属性中
public class TokenFilter implements GlobalFilter {


    private  long tokenExpiration; //有效时间,单位毫秒 1000毫秒 == 1秒
    private  String tokenSignKey;  //当前程序签名秘钥

    private static final List<String> WHITE_LIST = Arrays.asList(
            "/user/login",
            "/ws"
    );

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求路径
        String path = exchange.getRequest().getURI().getPath();

        // 如果路径在白名单中，直接放行
        if (WHITE_LIST.contains(path) || path.startsWith("/user/ws/")) {
            return chain.filter(exchange);
        }


        // 从请求头中提取用户 ID
        String token = exchange
                .getRequest()
                .getHeaders().getFirst("token");
        if (token != null) {
            JwtHelper jwtHelper = new JwtHelper();

            boolean expiration = jwtHelper.isExpiration(token ,tokenSignKey );
            if (!expiration) {
                String userId = jwtHelper.getUserId(token , tokenSignKey);
                // 将用户 ID 添加到下游请求的请求头中
                exchange = exchange.mutate()
                        .request(exchange.getRequest().mutate()
                                .header("userId", userId)
                                .build())
                        .build();
                return chain.filter(exchange);
            }
        }

        return unauthorizedResponse(exchange);
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange) {
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);



        try {
            JSONObject json = new JSONObject(R.fail(401 , "未经授权！"));
            byte[] bytes = json.toString().getBytes(StandardCharsets.UTF_8);
            return exchange.getResponse()
                    .writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(bytes)));
        } catch (Exception e) {
            return exchange.getResponse().setComplete();
        }
    }
}
